package tools;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.PropertyConfigurator;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
public class Dbutils {
    /**
     * 1.输出查询过程日志信息
     */
    public static void logs(){
        try {
            Properties properties = new Properties();
            FileInputStream fileInputStream = new FileInputStream("src/main/resources/config/log4j.properties");
            properties.load(fileInputStream);
            PropertyConfigurator.configure(properties);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 2.获取对象
     * @return
     */
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = null;
        try {
//        1.读取mybatis配置文件（）
            InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis-config0.xml");
//        2.获取sqlSession工厂对象
            SqlSessionFactory buildFac = new SqlSessionFactoryBuilder().build(resourceAsStream);
//        3.通过工厂获取对象
            sqlSession = buildFac.openSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sqlSession;
    }
    /**
     * 生成验证码
     * @return
     */

    public static String captcha(){
        Random random = new Random();
        String str="";
        char[] arr={'1','2','3','4','5','6','7','8','9','0','a','b','c','d','e','K','R','L','W','N'};
        for (int i = 0; i < 4; i++) {
            int j = random.nextInt(20);
            str+=arr[j];
        }
        return str;
    }
}
